/*
 */

package com.railway.news.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.org.rapid_framework.page.Page;
import com.railway.common.base.BaseManager;
import com.railway.common.base.EntityDao;
import com.railway.common.base.IdGenerator;
import com.railway.news.dao.INewsDao;
import com.railway.news.model.News;
import com.railway.news.service.INewsManager;
import com.railway.news.util.HTMLParserHelper;
import com.railway.news.util.NewsCfgManager;
import com.railway.news.util.PDFContentHelper;
import com.railway.news.util.XMLContentHelper;
import com.railway.news.vo.query.NewsQuery;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * @author jiangcheng
 * @version 1.0
 * @since 1.0
 */

@Service("newsManager")
@Transactional
public class NewsManagerImpl extends BaseManager<News, java.lang.String>
		implements INewsManager {

	private INewsDao newsDao;

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写 */
	public void setNewsDao(INewsDao dao) {
		this.newsDao = dao;
	}

	public EntityDao getEntityDao() {
		return (EntityDao) this.newsDao;
	}

	@Transactional(readOnly = true)
	public Page findPage(NewsQuery query) {
		return newsDao.findPage(query);
	}

	@Transactional(readOnly = true)
	public News getById(java.lang.String id) {
		return super.getById(id);
	}

	@Transactional
	public void removeByIdAndPath(String path, java.lang.String id) {

		super.removeById(id);
		// 同时要把文件删除掉
		try {

			XMLContentHelper.deleteContent(NewsCfgManager.getNewsPubDir()
					+ path);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/** 插入数据 */
	@Transactional
	public void save(News entity) {
		// 先构造个id
		String newsid = IdGenerator.genUUIDStr();
		entity.setId(newsid);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String p = sdf.format(new Date(System.currentTimeMillis()));
		// 在这里将内容保存为文件
		String name = newsid + ".xml";

		entity.setContentHtml(p + File.separator + name);
		// 先把内容缓存住
		String cachedcontent = entity.getContentText();
		// 清空
		entity.setContentText("");
		// 将新闻的除内容外的信息保存到数据库里
		newsDao.save(entity);//        
		try {
			// 解析图片路径接口
			HTMLParserHelper.parse(cachedcontent);
			File f = new File(NewsCfgManager.getNewsPubDir() + p);
			if (!f.exists()) {
				f.mkdir();
			}
			XMLContentHelper.createNewsContent(NewsCfgManager.getNewsPubDir()
					+ p + File.separator + name, newsid, cachedcontent);
			// 将新闻保存为Html
			Writer out = null;
			try {
				Configuration cfg = new Configuration();

				cfg.setDirectoryForTemplateLoading(new File(NewsCfgManager
						.getNewsPubDir())); // 设置读取模板文件的目录

				Template t = cfg.getTemplate("newstemplate.ftl"); // 读取文件名为newstemplate.ftl的模板

				Map root = new HashMap(); // 存储数据
				root.put("newstitle", "默认标题");
				root.put("newscreatetime", "默认时间");
				root.put("newscontent", cachedcontent);
				out = new OutputStreamWriter(new FileOutputStream(
						NewsCfgManager.getNewsPubDir() + p + File.separator
								+ newsid + ".html"), "GBK"); // 输出流

				t.process(root, out); // 动态加载root中的数据到Test.html。数据在模板中定义好了。
			} catch (Exception e1) {
				e1.printStackTrace();
			} finally {
				if (out != null) {
					out.flush();
					out.close();
				}
			}

			// 将新闻内容保存为PDF文件
			StringReader strReader = new StringReader(cachedcontent);
			//			
			PDFContentHelper.generatePDF_2(new File(NewsCfgManager
					.getNewsPubDir()
					+ p + File.separator + newsid + ".pdf"), NewsCfgManager
					.getNewsPubDir()
					+ p + File.separator + newsid + ".html");
			
			PDFContentHelper.generatePDF_1(new File(NewsCfgManager
					.getNewsPubDir()
					+ p + File.separator + newsid + "1.pdf"), strReader);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/** 更新数据 */
	@Transactional
	public void update(News entity) {
		String contentHtml = entity.getContentHtml();
		// 先把内容缓存住
		String cachedcontent = entity.getContentText();
		// 清空
		entity.setContentText("");
		super.update(entity);
		try {
			XMLContentHelper.modifyContent(NewsCfgManager.getNewsPubDir()
					+ contentHtml, entity.getId(), cachedcontent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Transactional(readOnly = true)
	public boolean isUnique(News entity, String uniquePropertyNames) {
		return super.isUnique(entity, uniquePropertyNames);
	}

	@Transactional(readOnly = true)
	public List<News> findAll() {
		return super.findAll();
	}

	public static void main(String[] args) {
		News n = new News();
		n.setContentText("asfddsafsadf");
		new NewsManagerImpl().save(n);
		System.out.println("HTML页面生成完毕!");

	}

	public List<News> findByTitle(String title) {
		return newsDao.findByTitle(title);
	}

	public String getNewContentById(String path, String id) {
		try {

			return XMLContentHelper.queryContent(NewsCfgManager.getNewsPubDir()
					+ path, id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	@Transactional(readOnly = true)
	public Page findPageLike(NewsQuery query) {
		return newsDao.findPageLike(query);
	}

}
